package com.doudou.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.net.URL;


@Component
public class CorsResponseFilter extends ZuulFilter {

    /**
     *返回布尔值来判断该过滤器是否要执行。可以通过此方法来执行过滤器的有效范围
     */
    private Logger logger = LoggerFactory.getLogger(CorsResponseFilter.class);

    @Override
    public String filterType() {
        /*
        pre：可以在请求被路由之前调用
        route：在路由请求时候被调用
        post：在route和error过滤器之后被调用
        error：处理请求时发生错误时被调用
        * */
        // 前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //// 优先级为0，数字越大，优先级越低
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();
        //解决Access-Control-Allow-Origin设置为* 异常
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            URL url = null;
            try {
                url = new URL(referer);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            String origin = url.getProtocol() + "://" + url.getHost();
            response.addHeader("Access-Control-Allow-Origin", origin);
        } else {
            response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        }

        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        response.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        //处理复杂请求
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(200);
            return null;
        }
        return null;
    }

}
